package com.learn.authentication.filters;

import com.learn.authentication.pojo.LogUser;
import com.learn.authentication.pojo.User;
import com.learn.authentication.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/06
 * @description Jwt的token认证过滤器
 * OncePerRequestFilter 是spring自带的过滤器, 保证只过滤一次
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 解析token获取userId
        String userId;
        try {
            userId = JwtUtil.getCurrentUserId(token);
        } catch (Exception e) {
            throw new RuntimeException("token验证失败");
        }
        if (!StringUtils.hasText(userId)) { // 应该不可能为null，但是以防万一
            throw new RuntimeException("token验证失败");
        }

        //查询redis数据库的用户信息
        // 存的时候存多了数据，先这样处理@JsonIgnoreProperties(ignoreUnknown = true)
        LogUser loginUser = (LogUser) redisTemplate.opsForValue().get("login_" + userId);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("请先登录");
        }

        // 封装成Authentication对象，已认证时可以直接向principal传入UserDetails对象
        // super.setAuthenticated(true);是使用三个参数的构造方法的原因
        // TODO 第三个参数是指权限信息
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginUser, null, loginUser.getAuthorities());

        // 存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }
}
